from werkzeug.security import generate_password_hash
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.exc import IntegrityError
from sqlalchemy import select, delete
from fastapi import HTTPException
from .models import UserModel
import uuid


# 用户模型增删改查
class UserModelCrud:
    # 创建用户
    @staticmethod
    async def create_user(db: AsyncSession, user: dict, model, return_msg: str):
        try:
            # 使用异步事务进行操作
            async with db.begin():
                user_info = user
                print("路由中获取的数据:", user_info)
                select_user, msg = await QueryCrud.get_one_info(db=db, select_model=UserModel,
                                                                select_info=user_info['account'],
                                                                select_model_info=UserModel.account)
                if select_user:
                    raise HTTPException(status_code=400, detail={"code": 401,
                                                                 "success": False,
                                                                 "msg": "用户已存在"})
                # 创建用户模型对象
                user_info['uuid'] = uuid.uuid4()
                user_info['password'] = generate_password_hash(user_info['password'])
                print("写入数据库的数据:", user_info)
                db_user = model(**user_info)
                # 将用户对象添加到数据库会话
                db.add(db_user)
                # 提交事务
            await db.commit()
            return True, {"code": 200, "success": False, "msg": return_msg}
        except IntegrityError as e:
            return False, {"code": 500, "success": False, "msg": "服务器错误", "info": str(e)}

    # 编辑
    @staticmethod
    async def update_user(db: AsyncSession, current_user: dict, user: dict, model, return_msg: str):
        try:
            # 使用异步事务进行操作
            async with db.begin():
                user_info = user
                token_info = current_user
                if user_info['account'] != token_info['account']:
                    raise HTTPException(status_code=403,
                                        detail={"code": 403, "success": False, "msg": "用户名不允许修改"})
                print("路由中获取的数据:", user_info)
                select_user, msg = await QueryCrud.get_one_info(db=db, select_info=token_info['uuid'],
                                                                select_model=model,
                                                                select_model_info=model.uuid)
                if not select_user:
                    raise HTTPException(status_code=400, detail={"code": 400, "success": False, "msg": "用户不存在"})

                # 编辑用户信息
                user_info['id'] = msg.id
                user_info['uuid'] = msg.uuid
                user_info['password'] = generate_password_hash(user_info['password'])
                print("写入数据库的数据:", user_info)
                update_user = model(**user_info)
                await db.merge(update_user)
            # 提交事务
            await db.commit()
            return True, {"code": 201, "success": True, "msg": return_msg}
        except IntegrityError as e:
            return False, {"code": 500, "success": False, "msg": "服务器错误", "info": str(e)}

    # 删除（单个/批量都可以）
    @staticmethod
    async def delete_user(db: AsyncSession, current_user: dict, model, return_msg: str):
        try:
            # 使用异步事务进行操作
            async with db.begin():
                token_info = current_user
                print("路由中获取的数据:", token_info)
                # 删除用户
                delete_user = delete(model).where(model.uuid == token_info['uuid'])
                await db.execute(delete_user)
            # 提交事务
            await db.commit()
            return True, {"code": 201, "success": True, "msg": return_msg}
        except IntegrityError as e:
            return False, {"code": 500, "success": False, "msg": "服务器错误", "info": str(e)}


# 数据库查询
class QueryCrud:
    # 查询所有信息
    @staticmethod
    async def get_all_info(select_model, db: AsyncSession):
        # 使用异步 SQL 查询语句
        query_all = select(select_model)
        # 执行查询语句
        query_all = await db.execute(query_all)
        # 获取查询结果
        query_all = query_all.scalars().all()
        return query_all

    # 根据查询条件，查询单条信息
    @staticmethod
    async def get_one_info(select_info: str, select_model, select_model_info, db: AsyncSession):
        # 使用异步 SQL 查询语句
        query_one = select(select_model).where(select_model_info == select_info)
        query_one = await db.execute(query_one)
        # 执行查询并返回结果
        result = query_one.scalar()
        if result:
            # print(result)
            return True, result
        return False, {}
